package com.lsy.system.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lsy.handler.BusinessException;
import com.lsy.response.ResultCode;
import com.lsy.system.entity.Department;
import com.lsy.system.entity.User;
import com.lsy.system.enums.UserStatusEnum;
import com.lsy.system.enums.UserTypeEnum;
import com.lsy.system.mapper.DepartmentMapper;
import com.lsy.system.mapper.UserMapper;
import com.lsy.system.service.DepartmentService;
import com.lsy.system.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lsy.utils.JWTUtils;
import com.lsy.utils.MD5Utils;
import com.lsy.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author lsy
 * @since 2022-02-12
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public IPage<User> findUserPage(Page<User> page, QueryWrapper<User> wrapper) {
        return this.baseMapper.findUserPage(page, wrapper);
    }

    @Override
    public void addUser(User user) {
        String username = user.getUsername();
        Long departmentId = user.getDepartmentId();
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        Integer count = this.baseMapper.selectCount(wrapper);
        if (count != 0) {
            //账号已经存在
            throw new BusinessException(ResultCode.USER_ACCOUNT_ALREADY_EXIST.getCode(),
                    ResultCode.USER_ACCOUNT_ALREADY_EXIST.getMessage());
        }
        Department department = departmentMapper.selectById(departmentId);
        if (department == null) {
            throw new BusinessException(ResultCode.DEPARTMENT_NOT_EXIST.getCode(),
                    ResultCode.DEPARTMENT_NOT_EXIST.getMessage());
        }
        String salt = UUID.randomUUID().toString().substring(0, 32);
        user.setPassword(passwordEncoder.encode(user.getPassword()));
//        user.setModifiedTime(new Date());
//        user.setCreateTime(new Date());
        //设置盐值  在这里其实已经没有意义了,因为spring security加密的密码默认已经提供了盐值
        user.setSalt(salt);
        //添加的用户默认是普通用户
        user.setType(UserTypeEnum.SYSTEM_USER.getTypeCode());
        //添加的用户默认启用
        user.setStatus(UserStatusEnum.AVAILABLE.getStatusCode());
        this.baseMapper.insert(user);
    }

    @Override
    public void exportUserExcel(HttpServletResponse response, List<User> users) throws IOException {

        //----- 写入excel文件
        //1。定义文件的名称
        String exportFileName = "TbUserInfo.xlsx";
        //2。设置响应头的字符集（如果没有设置,导出来可能就是乱码)
        response.setCharacterEncoding("UTF-8");
        //3。设置导出的格式
        response.setContentType("application/vnd.ms-excel");
        //4。设置导出文件的名称
        response.addHeader("Content-Disposition", "attachment;filename=" + exportFileName);
        //5。执行导出的操作
        EasyExcel.write(response.getOutputStream(), User.class)
                .sheet("用户信息")
                //自动列宽(都是参数自动列宽合并单元格...)
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                .doWrite(users);
    }

    @Override
    public List<User> findExportUser(UserVO userVO) {
        return this.baseMapper.findExportUser(userVO);
    }

    @Override
    public Page<User> findUserList(Page<User> page, UserVO userVO) {
        List<User> userList = this.baseMapper.findUserList(page, userVO);
        page.setRecords(userList);
        return page;
    }

    /**
     * 导出的时候根据条件查询用户信息
     *
     * @param userVO
     * @return
     */
    @Override
    public List<User> findUsers(UserVO userVO) {
        return this.baseMapper.findUsers(userVO);
    }

    /**
     * 在这里需要生成token并且进行返口
     *
     * @param username
     * @param password
     * @return
     */
    @Override
    public String login(String username, String password) {
        //定义一个token进行返回
        String token = null;
        //1。根据用户名查询用户信息
        User user = this.baseMapper.loadUserByUsername(username);
        if (user != null) {
            //2.需要获取用户的密码跟盐
            String salt = user.getSalt();
            String userPassword = user.getPassword();
            //3.对原始密码进行加密加盐的操作
            String encryptionPassword = MD5Utils.md5Encryption(password, salt);
            //4。对比数据库的密码和加密之后的密码,判断是否相等
            if (userPassword.equals(password)) {
                //5.相等则生成token
                token = JWTUtils.sign(username, password);
                System.out.println(token+"______"+username+"_______"+encryptionPassword);
                //6.还需要将token存入到shiro的登录管理器中
            } else {
                throw new BusinessException(ResultCode.USER_CREDENTIALS_ERROR.getCode(),
                        ResultCode.USER_CREDENTIALS_ERROR.getMessage());
            }
        }else {
            throw new BusinessException(ResultCode.USER_ACCOUNT_NOT_EXIST.getCode(),
                    ResultCode.USER_ACCOUNT_NOT_EXIST.getMessage());
        }

        return token;

    }
}
